package zl_service

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/goravel/framework/facades"
	"github.com/goravel/framework/support/carbon"
	"goravel/app/models"
	"io/ioutil"
	"net/http"
)

type CategoryService struct {
}
type DataPaginate struct {
	Page         int        `json:"page"`
	PageSize     int        `json:"pageSize"`
	TotalRecords int        `json:"totalRecords"`
	List         []Category `json:"list"`
}

type Category struct {
	ID            string `json:"id"`
	ShopCode      string `json:"shopcode"`
	CategoryCode  string `json:"categorycode"`
	CategoryName  string `json:"categoryname"`
	CreateUser    string `json:"createuser"`
	CreateTime    string `json:"createtime"`
	UpdateUser    string `json:"updateuser"`
	UpdateTime    string `json:"updatetime"`
	Required      string `json:"required"`
	OrderNum      string `json:"ordernum"`
	ParentCode    string `json:"parentcode"`
	IsShow        string `json:"isshow"`
	Level         string `json:"level"`
	Category1Code string `json:"category1code"`
	Category2Code string `json:"category2code"`
	Category3Code string `json:"category3code"`
	Category4Code string `json:"category4code"`
	Category1Name string `json:"category1name"`
	Category2Name string `json:"category2name"`
	Category3Name string `json:"category3name"`
	Category4Name string `json:"category4name"`
}
type CategoryData struct {
	ErrorMsg  string       `json:"errorMsg"`  // 错误信息
	ErrorCode string       `json:"errorCode"` // 错误码
	Success   string       `json:"success"`   // 是否成功
	Data      DataPaginate `json:"data"`
}

const (
	BASE_URL = "https://api.zhonglunnet.com"
	//APP_KEY    = "APPKEY202411191904001EO5VEP1EP" //总部
	//APP_SECRET = "SECRET20241119190400TBQO9A7W64" //总部
)
const (
	APP_KEY    = "APPKEY20241122105110S9KC86OVIV" //自营门店001
	APP_SECRET = "SECRET2024112210511077MNKIOKP8" //自营门店001
)
const (
	CATEGORY_URL = "/zl.open.api.dcms.category.page.v5/1.0.0/action"
)

// 分页查询商品类型
func (b *CategoryService) SyncCategory() (error, DataPaginate) {
	url := BASE_URL + CATEGORY_URL
	client := &http.Client{}
	// 请求参数结构体，对应要发送的JSON数据格式
	requestBody := struct {
		AppKey   string `json:"appkey"`
		Signtime string `json:"signtime"`
		PageSize int    `json:"pageSize"`
	}{
		AppKey:   APP_KEY,
		Signtime: carbon.NewDateTime(carbon.Now()).Format("Y-m-d H:i:s"),
		PageSize: 100,
	}
	bodyBytes, _ := json.Marshal(requestBody)
	stringToSign := fmt.Sprintf("%s&appsecret=%s", string(bodyBytes), APP_SECRET)
	upperSign := ComputeMD5AndToUpper(stringToSign)
	req, err := http.NewRequest("POST", url, bytes.NewBuffer(bodyBytes))
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Request-Sign", upperSign)
	if err != nil {
		return err, DataPaginate{}
	}
	body, err := client.Do(req)
	if err != nil {
		return err, DataPaginate{}
	}
	//将body
	res, err := ioutil.ReadAll(body.Body)
	if err != nil {
		return err, DataPaginate{}
	}
	var resp CategoryData
	err = json.Unmarshal(res, &resp)
	db := facades.Orm().Query()
	db.Exec("truncate table zl_categories")
	var categories []models.Category
	for _, v := range resp.Data.List {
		category := models.Category{
			ZID:           v.ID,
			ShopCode:      v.ShopCode,
			CategoryCode:  v.CategoryCode,
			CategoryName:  v.CategoryName,
			CreateUser:    v.CreateUser,
			CreateTime:    v.CreateTime,
			UpdateUser:    v.UpdateUser,
			UpdateTime:    v.UpdateTime,
			Required:      v.Required,
			OrderNum:      v.OrderNum,
			ParentCode:    v.ParentCode,
			IsShow:        v.IsShow,
			Level:         v.Level,
			Category1Code: v.Category1Code,
			Category2Code: v.Category2Code,
			Category3Code: v.Category3Code,
			Category4Code: v.Category4Code,
			Category1Name: v.Category1Name,
			Category2Name: v.Category2Name,
			Category3Name: v.Category3Name,
			Category4Name: v.Category4Name,
		}
		categories = append(categories, category)
	}
	db.Create(&categories)
	return nil, resp.Data
}
